package com.smartcar.gateway.filters;

import com.smartcar.common.constants.TokenConstants;
import com.smartcar.common.utils.JwtUtils;
import com.smartcar.common.utils.StringUtils;
import com.smartcar.gateway.config.IgnoreWhiteConfig;
import com.smartcar.gateway.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class SystemFilter implements Ordered, GatewayFilter {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IgnoreWhiteConfig ignoreWhiteConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取白名单列表
        List<String> whites = ignoreWhiteConfig.getWhites();
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (StringUtils.matches(path, whites)) {
            return chain.filter(exchange);
        }
        //获取token
        String token = request.getHeaders().getFirst(TokenConstants.TOKEN);
        // token不能为空
        if (StringUtils.isEmpty(token)) {
            return GatewayUtils.errorResponse(exchange, "token不存在", HttpStatus.MULTI_STATUS);
        }
        // 验证token合法性
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            return GatewayUtils.errorResponse(exchange, "token不合法", HttpStatus.MULTI_STATUS);
        }
        // 获取userKey
        String userKey = JwtUtils.getUserKey(token);
        // 验证token过期
        if (!redisTemplate.hasKey(TokenConstants.TOKEN + userKey)) {
            return GatewayUtils.errorResponse(exchange, "token过期，请重新登录", HttpStatus.MULTI_STATUS);
        }
        // 校验通过 --> 放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
